package com.lb.trac.controller.common.loaders;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.CollectionUtils;

import com.lb.trac.pojo.Tickets;
import com.lb.trac.pojo.Utenti;
import com.lb.trac.pojo.condition.TicketFinderByIdTicket;
import com.lb.trac.service.SearchService;
import com.lb.trac.util.SQLCondition;

public class LoadManageTicketData implements HttpObjectsLoader {

	private SearchService searchService;

	public void load(HttpServletRequest request, HttpServletResponse response) {
		Utenti utenteLoggato = (Utenti) request.getSession()
				.getAttribute("loginForm");

		if (request.getParameter("idStato") != null) {
			request.setAttribute("idStato", request.getParameter("idStato"));
		}
		if (request.getParameter("idUtenteAssegnatario") != null) {
			request.setAttribute("idUtenteAssegnatario",
					request.getParameter("idUtenteAssegnatario"));
		}

		// if (request.getSession(false).getAttribute("stati") == null) {
		// StatiView[] stati = getSearchService().findAllStati();
		// request.getSession(false).setAttribute("stati", stati);
		// }

		if (utenteLoggato.getProfilo().getDescrizione()
				.equalsIgnoreCase("DEVELOPER")) {
			if (request.getSession(false).getAttribute("assegnatari") == null) {
				String idTicket = request.getParameter("idTicket");
				if (idTicket != null && !idTicket.equals("")) {
					SQLCondition sqlCondition = new TicketFinderByIdTicket(
							idTicket);
					Tickets tickets = getSearchService().find(new Tickets[0],
							sqlCondition, Tickets.class)[0];
					Utenti[] utentiViews = searchService.findUtentiAbilitatiProgettoByProfilo(tickets
									.getIdProgetto().toPlainString(),
									utenteLoggato.getProfilo());
					request.getSession(false).setAttribute("assegnatari",
							CollectionUtils.arrayToList(utentiViews));
				}
			}
		}
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

}
